package com.gxuwz.endrskyweather.viewmodel;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.gxuwz.endrskyweather.repository.FavoriteRepository;

public class FavoriteViewModel extends AndroidViewModel {
    private FavoriteRepository repository;
    private MutableLiveData<Integer> addFavoriteResult = new MutableLiveData<>();

    public FavoriteViewModel(Application application) {
        super(application);
        repository = new FavoriteRepository(application);
    }

    public MutableLiveData<Integer> getAddFavoriteResult() {
        return addFavoriteResult;
    }

    public void addFavoriteCity(String areaCode, String areaName) {
        new Thread(() -> {
            SQLiteDatabase db = null;
            try {
                db = repository.getDBHelper().getWritableDatabase();
                int result = repository.addFavoriteCity(areaCode, areaName);
                addFavoriteResult.postValue(result);
//                if (result == 1) {
//                    // 想要收藏的城市已经存在
//                    Toast.makeText(getApplication(), "该城市已经收藏过了", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                if (result == -1) {
//                    // 收藏失败
//                    Toast.makeText(getApplication(), "收藏失败", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                if (result == 0) {
//                    // 收藏成功
//                    Toast.makeText(getApplication(), "收藏成功", Toast.LENGTH_SHORT).show();
//                }
//                // 调试用：查询收藏表的所有数据
//                db = repository.getDBHelper().getReadableDatabase();
//                cursor = repository.getAllFavorites();
//                while (cursor.moveToNext()) {
//                    String areaCode1 = cursor.getString(cursor.getColumnIndex("favorite_area_code"));
//                    String areaName1 = cursor.getString(cursor.getColumnIndex("favorite_area_cn"));
//                    System.out.println("收藏表：" + areaCode1 + " " + areaName1);
//                }
                // 更新 FavoriteCitesNonDefault 的 LiveData
            } catch (Exception e) {
                Log.e("FavoriteViewModel", "addFavoriteCity: ", e);
            } finally {
                if (db != null) db.close();
            }
        }).start();
    }


}
